package com.edu.gateway.utils;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * 加密工具类
 */
@Slf4j
public class EncryptUtil {

    public static final String SHA256="HmacSHA256";

    private static final char[] HEX_CHARS =
            {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    public static String encodeByHmacSHA1(String stringToSign,String secret){
        String sign=null;
        try {
            Mac hmacSha1 = Mac.getInstance("HmacSHA1");
            byte[] keyBytes = secret.getBytes(Charset.forName("UTF-8"));
            hmacSha1.init(new SecretKeySpec(secret.getBytes("UTF-8"), 0, keyBytes.length, "HmacSHA1"));
            byte[] md5Result = hmacSha1.doFinal(stringToSign.getBytes("UTF-8"));
            sign = Base64.getEncoder().encodeToString(md5Result);
        } catch (Exception e) {
            log.error("encodeByHmacSHA1 stringToSign:{},appSecret:{}",stringToSign,secret);
           log.error("encodeByHmacSHA1 error:",e);
        }
        return sign;
    }
    public static String encodeByHmacSHA256(String stringToSign,String secret){
        String sign=null;
        try {
            Mac hmacSha256 = Mac.getInstance("HmacSHA256");
            byte[] keyBytes = secret.getBytes(Charset.forName("UTF-8"));
            hmacSha256.init(new SecretKeySpec(secret.getBytes("UTF-8"), 0, keyBytes.length, "HmacSHA256"));
            byte[] md5Result = hmacSha256.doFinal(stringToSign.getBytes("UTF-8"));
            sign = Base64.getEncoder().encodeToString(md5Result);

        } catch (Exception e) {
            log.error("encodeByHmacSHA256 stringToSign:{},secret:{}",stringToSign,secret);
            log.error("encodeByHmacSHA256 error",e);
        }
        return sign;
    }
    public static String encodeByMD5(String plainText) {
        byte[] secretBytes = null;
        try {
            secretBytes = MessageDigest.getInstance("md5").digest(
                    plainText.getBytes());
        } catch (NoSuchAlgorithmException e) {
            log.error("encodeByMD5 error",e);
            return null;
        }
        if(null==secretBytes){
            return null;
        }
        return new String(encodeHex(secretBytes));
    }
    private static char[] encodeHex(byte[] bytes) {
        char chars[] = new char[32];
        for (int i = 0; i < chars.length; i = i + 2) {
            byte b = bytes[i / 2];
            chars[i] = HEX_CHARS[(b >>> 0x4) & 0xf];
            chars[i + 1] = HEX_CHARS[b & 0xf];
        }
        return chars;
    }

}
